package com.chungkui.check.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: jason
 * @Date: 2019/12/27 19:55
 * @Version 1.0
 */
public class JsonUtil {
    private JsonUtil() {
    }

    private static final ObjectMapper MAPPER = new ObjectMapper();
    private static final Logger log = LoggerFactory.getLogger(JsonUtil.class);

    public static Map<String, Object> json2map(String json) {
        Map<String, Object> obj;
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            MAPPER.configure(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS, true);
            obj = MAPPER.readValue(json, Map.class);
        } catch (Exception e) {
            log.error(String.format("json2map error {}", json, e));
            return null;
        }

        return obj;
    }

    public static String obj2json(Object obj) {
        String json = "";
        try {
            json = MAPPER.writeValueAsString(obj);
        } catch (Exception e) {
            log.error("obj2json failed, obj is: {}", obj, e);
        }
        return json;
    }

    public static <T> T jsonToObject(String json, Class<T> clazz) {
        Object obj = null;
        try {
            MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            MAPPER.configure(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS, true);
            MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            obj = MAPPER.readValue(json, clazz);
        } catch (Exception e) {
            log.error(String.format("jsonToObject error :{} class :{}", json, clazz.toString()), e);
        }
        return (T) obj;
    }

    public static Map<String, Object> bean2map(Object obj) {
        try {
            if (obj instanceof Map) {
                return (Map) obj;
            }
            Map returnMap = BeanUtils.describe(obj);
            returnMap.remove("class");
            return returnMap;
        } catch (Exception e) {
            log.error("bean2map error", e);
        }
        return new HashMap(0);


    }
}
